package com.zhang.flink.exercise;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.Iterator;

/**
 * @title:
 * @author: zhangyifan
 * @date: 2022/10/12 15:10
 */
public class SlidingWindowTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Tuple2<Integer, Long>>() {
                    @Override
                    public Tuple2<Integer, Long> map(String value) throws Exception {
                        String[] fields = value.split(" ");
                        return Tuple2.of(Integer.parseInt(fields[0]), Long.parseLong(fields[1]) * 1000L);
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple2<Integer, Long>>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<Integer, Long>>() {
                                    @Override
                                    public long extractTimestamp(Tuple2<Integer, Long> element, long recordTimestamp) {
                                        return element.f1;
                                    }
                                })
                )
                .keyBy(r -> 1)
                .window(SlidingEventTimeWindows.of(Time.seconds(5L), Time.seconds(1L)))
                .process(new ProcessWindowFunction<Tuple2<Integer, Long>, String, Integer, TimeWindow>() {
                    @Override
                    public void process(Integer integer, ProcessWindowFunction<Tuple2<Integer, Long>, String, Integer, TimeWindow>.Context context, Iterable<Tuple2<Integer, Long>> elements, Collector<String> out) throws Exception {
                        Iterator<Tuple2<Integer, Long>> iterator = elements.iterator();

                        int sum = 0;
                        while (iterator.hasNext()) {
                            Tuple2<Integer, Long> next = iterator.next();
                            System.out.println(next);
                            sum += next.f0;
                        }
                        StringBuilder result = new StringBuilder("-------------------------" + new Timestamp(context.window().getStart()) + "-------------------------\n");
                        result.append("result:" + sum +"-----"+ context.currentWatermark() +"\n");
                        result.append("-------------------------" + new Timestamp(context.window().getEnd()) + "-------------------------\n");

                        out.collect(result.toString());
                    }
                })
                .print();


        env.execute();
    }
}
